<template>
  <div>
    <excel-paste
      :columnsExcel="columns"
      :exportXlsTemplateUrl="excel.templateUrl"
      :excelVisible="excel.visible"
      :excelConfirmLoading="excel.loading"
      @handleOkExcel="handleOkExcel"
      @handleCancelExcel="handleCancelExcel"
    ></excel-paste>
    <div style="widht: 100%; height: 30px;border:1px solid rgb(0,0,0,0)" v-if="showTitle || (strNotNull(projectBuildId) && editable)">
      <div v-if="showTitle" class="info-title" style="float:left;width:200px;">
        <img src="@/assets/category-blue.png" alt="" />
        <span>项目竣工验收目标</span>
      </div>
      <a-row type="flex" justify="end" v-if="strNotNull(projectBuildId) && editable" style="margin-top:10px;">
        <a-col>   
          <!-- <a-button size="small" @click="doSave">保存</a-button> -->
          <a-button size="small" @click="doImpl" style="margin-left: 5px">导入</a-button>
          <a-button size="small" @click="doExport" style="margin-left: 5px">导出</a-button>
        </a-col>
      </a-row>
    </div>
    <a-table :rowKey="rowKey" :columns="tabColums" :data-source="data" :pagination="false" bordered>
      <template slot="descript" slot-scope="text, record">
        <a-textarea
          v-model="record.descript"
          :placeholder="showDescriptPlaceholder(record.type)"
          :auto-size="{ minRows: 1, maxRows: 20 }"
          :maxLength="500"
          v-if="editable"
        />
        <span v-else>{{record.descript}}</span>
      </template>
      <template slot="checkLogic" slot-scope="text, record">
        <a-textarea
          v-model="record.checkLogic"
          placeholder="请填写对指标达成的验证逻辑"
          :auto-size="{ minRows: 1, maxRows: 20 }"
          :maxLength="500"
          v-if="editable"
        />
        <span v-else>{{record.checkLogic}}</span>
      </template>
      <template slot="remark" slot-scope="text, record">
        <a-textarea
          v-model="record.remark"
          placeholder="备注说明"
          :auto-size="{ minRows: 1, maxRows: 20 }"
          :maxLength="500"
          v-if="editable"
        />
        <span v-else>{{record.remark}}</span>
      </template>

      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <a-icon v-if="record.firstOne" type="plus-circle" style="color: #31a0e1" @click="doAdd(record, index)" />
          <a-icon v-else type="minus-circle" style="color: red" @click="doDel(record, index)" />
        </div>
      </template>
    </a-table>
    <div class="tips" style="color:red;font-size:12px" v-if="path=='/projectbuildstup/baseInfo'">
      <div class="item">
        【指标说明】:填写具体要达成的项目验收的内容
      </div><div class="item">
        【检验逻辑】:填写如何来检验或验证这个指标是否达成的方式/方法/算法逻辑等
      </div>
    </div>
  </div>
</template>

<script>
import { strNotNull } from '@/utils/common.js'
import { filterObj, formatDate } from '@/utils/util';
import { getAction, postAction ,downFile} from '@/api/manage'
import ExcelPaste from '@/components/excelPaste/ExcelPaste'
export default {
  components: { ExcelPaste },
  name: 'ProjectCompleteAcceptTarget',
  props: {
    projectBuildId: {
      type: String,
      required: false,
      default: '',
    },
    changeId: {
      type: String,
      required: false,
      default: ''
    },
    editable: {
      type: Boolean,
      required: false,
      default: false,
    },
    showTitle: {
      type: Boolean,
      required: false,
      default: true,
    },
  },
  data() {
    return {
      rowKey: 'id',
      excel: {
        visible: false,
        loading: false,
        data: [],
        templateUrl: 'templates/excel/项目验收标准模板.xlsx',
      },
      data: [],
      gj: 0,
      yb: 0,
      tabColums: [],
      columns: [
        {
          title: '指标类型',
          dataIndex: 'type',
          width: '12%',
        },
        {
          title: '指标说明',
          dataIndex: 'descript',
          width: '30%',
          scopedSlots: { customRender: 'descript' },
        },
        {
          title: '核验逻辑',
          dataIndex: 'checkLogic',
          width: '30%',
          scopedSlots: { customRender: 'checkLogic' },
        },
        {
          title: '备注说明',
          dataIndex: 'remark',
          width: '15%',
          scopedSlots: { customRender: 'remark' },
        },
      ],
      urls: {
        list: '/projectCompleteAcceptTarget/listByProjectBuildId',
        export: '/projectCompleteAcceptTarget/export',
        save: '/projectCompleteAcceptTarget/save'
      },
      maxId: 0,
      addLastFlag: true,
      path:this.$route.path
    }
  },
  watch: {
    editable(){
      this.freshEditAble()
    }
  },
  mounted() {
    this.initData()
    this.initTabColums()
    this.freshEditAble()
  },
  methods: {
    showDescriptPlaceholder(type){
      if(type.indexOf('工艺指标')>-1){
        return '精度、温度等工艺参数要求，写具体参数或指标，不允许写【与在用工艺一样】';
      }
      if(type.indexOf('产能指标')>-1){
        return '生产效益、速度等，写具体数值或指标，不允许写【与在用产能一样】';
      }
      if(type.indexOf('效益指标')>-1){
        return '需写具体可量化指标，如节员2人或节水100吨或年收益100万，回收期0.5年';
      }
      if(type.indexOf('能耗指标')>-1){
        return '新增产能、新增生产线，新增独立工序及节能项目必有';
      }
      if(type.indexOf('其他关键指标')>-1){
        return '其他关键指标';
      }
      if(type.indexOf('一般质量指标')>-1){
        return '规范、卫生、培训等不影响使用的指标';
      }
    },
    doSave(){
      if(strNotNull(this.changeId)){
        this.$emit('doSave')
        return;
      }
      for(var i=0;i<this.data.length;i++){
        var item=this.data[i];
        if(strNotNull(item.descript) || strNotNull(item.checkLogic)){
          var preMsg = '【项目竣工验收指标】第'+(i+1)+'行,';
          if(!strNotNull(item.descript)){
            this.$message.warning(preMsg+'【指标说明】,不可为空')
            return
          }
          if(!strNotNull(item.checkLogic)){
            this.$message.warning(preMsg+'【核验逻辑】,不可为空')
            return
          }
        }
      }
      var formData={id:this.projectBuildId,changeId:this.changeId,projectCompleteAcceptTargets:this.data}
      postAction(this.urls.save, formData)
        .then((res) => {
          if (res.code == 200) {
            this.$emit('freshTargetTypes')
            this.$message.success('保存成功')
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        }).catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
    },
    getTargets(){
      return this.data
    },
    handleOkExcel(data) {
      if (data == null || data.length < 1) {
        this.$message.warning('未导入有效数据')
        this.excel.visible = false
        return
      }
      for (var i = 0; i < data.length; i++) {
        var d = data[i]
        var msg = '第【' + (i + 1) + '】行,'
        if (!strNotNull(d.type)) {
          this.$message.warning(msg + '指标类型不可为空')
          return
        }
      }
      data.forEach((d) => {
        var maxdata = this.getMaxData()
        for (var i = 0; i < maxdata.length; i++) {
          var arr = this.getTypeArr(maxdata[i].record.type)
          if (arr[1] == d.type) {
            var maxdataR = maxdata[i].record;
            if(strNotNull(maxdataR.descript) || strNotNull(maxdataR.descript) || strNotNull(maxdataR.descript)){
              this.doAdd(maxdata[i].record, maxdata[i].index, d.descript, d.checkLogic, d.remark)
            }else{
              this.data[maxdata[i].index].descript=d.descript
              this.data[maxdata[i].index].checkLogic=d.checkLogic
              this.data[maxdata[i].index].remark=d.remark
            }
            break
          }
        }
      })
      this.excel.visible = false
    },
    getMaxData() {
      var data = []
      for (var j = 0; j < this.data.length; j++) {
        var darr = this.getTypeArr(this.data[j].type)
        var add = true
        for (var i = 0; i < data.length; i++) {
          var arr = this.getTypeArr(data[i].record.type)
          if (arr[0] == darr[0] && arr[1] == darr[1]) {
            add = false
            if (arr[2] < darr[2]) {
              data[i].record = this.data[j]
              data[i].index = j
            }
          }
        }
        if (add) {
          data.push({ record: this.data[j], index: j })
        }
      }
      return data
    },
    handleCancelExcel() {
      this.excel.visible = false
    },
    doImpl() {
      this.excel.visible = true
    },
    doExport() {
      let fileName = '项目竣工验收指标'
      let dateStr = formatDate(new Date().getTime(), 'yyyy-MM-dd')
      fileName = `${dateStr}《${fileName}》`
      this.loading = true
      downFile(this.urls.export, { projectBuildId: this.projectBuildId }).then((data) => {
        this.loading = false
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    initTabColums() {
      this.tabColums.push({
        title: '指标大类',
        dataIndex: 'bigType',
        width: '8%',
        customRender: (value, row, index) => {
          const obj = {
            children: value,
            attrs: {},
          }
          if (row.type.indexOf('A01') > -1) {
            obj.attrs.rowSpan = this.gj
          } else if (row.type.indexOf('F01') > -1) {
            obj.attrs.rowSpan = this.yb
          } else {
            obj.attrs.rowSpan = 0
          }
          return obj
        },
      })
      this.columns.forEach((col) => {
        this.tabColums.push(col)
      })
    },
    freshEditAble(){
      if(this.editable && this.addLastFlag){
        this.tabColums.push({
          title: '操作',
          dataIndex: 'operation',
          width: '5%',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        })
        this.addLastFlag=false
      }
    },
    strNotNull(v) {
      return strNotNull(v)
    },
    getTypeArr(t) {
      var type = t.split('_')
      var f = type[0].substring(0, 1)
      var e = type[1]
      var n = type[0].substring(1, 3)
      var num = parseInt(n.substring(0, 1) == '0' ? n.substring(1, 2) : n)
      return [f, e, num]
    },
    doAdd(record, index, descript, checkLogic, remark) {
      var reArr = this.getTypeArr(record.type)
      var index_ = 0
      var maxNum = ++reArr[2]
      this.data.forEach((item) => {
        var itemArr = this.getTypeArr(item.type)
        if (itemArr[0] == reArr[0] && itemArr[1] == reArr[1] && itemArr[2] >= maxNum) {
          index = index_
          maxNum = ++itemArr[2]
        }
        index_++
      })
      if (record.bigType == '关键质量指标') {
        this.gj++
      }
      if (record.bigType == '一般质量指标') {
        this.yb++
      }
      this.data.splice(index + 1, 0, {
        id: ++this.maxId,
        bigType: record.bigType,
        type: reArr[0] + (maxNum < 10 ? '0' + maxNum : maxNum) + '_' + reArr[1],
        descript: descript,
        checkLogic: checkLogic,
        remark: remark,
        firstOne: false,
      })
    },
    doDel(record, index) {
      var reArr = this.getTypeArr(record.type)
      var data_ = []
      this.data.forEach((item) => {
        var itemArr = this.getTypeArr(item.type)
        if (itemArr[0] == reArr[0] && itemArr[1] == reArr[1]) {
          if (itemArr[2] < reArr[2]) {
            data_.push(item)
          } else if (itemArr[2] > reArr[2]) {
            itemArr[2]--
            item.type = itemArr[0] + (itemArr[2] < 10 ? '0' + itemArr[2] : itemArr[2]) + '_' + itemArr[1]
            data_.push(item)
          } else {
            if (record.bigType == '关键质量指标') {
              this.gj--
            }
            if (record.bigType == '一般质量指标') {
              this.yb--
            }
          }
        } else {
          data_.push(item)
        }
      })
      this.data = data_
    },
    initData() {
      getAction(this.urls.list, { projectBuildId: this.projectBuildId,projectChangeId: this.changeId }).then((res) => {
        if (res.code == 200) {
          res.result.forEach((item) => {
            if (item.id > this.maxId) {
              this.maxId = item.id
            }
            if (item.bigType == '关键质量指标') {
              ++this.gj
            } else {
              ++this.yb
            }
          })
          this.data = res.result
        } else {
          this.$message.warning('加载数据失败:' + res.message)
        }
      })
    },
  },
}
</script>

</script>
<style scoped>
/deep/ .ant-table .ant-table-tbody .ant-table-row td {
    padding: 2px 2px !important;
}
.editable-row-operations a {
  margin-right: 8px;
}
.info-title {
      display: flex;
      align-items: center;
      margin: 10px 0;
    }
.info-title > img {
        margin-right: 5px;
      }
.info-title > span {
        font-size: 16px;
        font-weight: 900;
        color: black;
      }

</style>
